package com.example.app.controller;

import com.example.app.entity.Medication;
import com.example.app.service.DeepSeekService;
import com.example.app.service.MedicationService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import com.example.app.service.DeepSeekService;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/medications")
@RequiredArgsConstructor
public class MedicationController {

    private final MedicationService medicationService;
    private final DeepSeekService deepSeekService;
    private final ObjectMapper objectMapper = new ObjectMapper();
    // 获取用户所有锻炼记录
    @GetMapping("/user/{userId}")
    public List<Medication> getMedicationsByUserId(@PathVariable Long userId) {
        return medicationService.getMedicationsByUserId(userId);
    }
    @GetMapping("/user/{userId}/{date}")
    public List<Medication> getMedicationsByUserIdAndDate(
            @PathVariable Long userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        return medicationService.getMedicationsByUserIdAndDate(userId,date);
    }

    // 获取用户在某天的锻炼记录
    @PostMapping("/generate")
    public List<Medication> generateMedication(@RequestBody Map<String, String> request) throws Exception {
        Long userId = Long.parseLong(request.get("userId"));
        String idea = request.get("idea");

        String sb = "请根据健康信息以及用药计划生成标准结构化 JSON 格式用药计划(至少列出7天且相同时间的用药合并在一起)（只需输出json即可），字段包括：context（药品名称及用量，例如：肠炎宁1粒）、time（时分秒，24小时制）、date（格式为YYYY-MM-DD）。\n" +
                "用药计划：" + idea;
        String fullPrompt = deepSeekService.buildMedicationPrompt(userId, sb);
        String jsonAnswer = deepSeekService.answerQuestion(fullPrompt, false).block();

        Pattern pattern = Pattern.compile("\\[.*?\\]", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(jsonAnswer);
        if (matcher.find()) {
            jsonAnswer = matcher.group(); // 提取中括号及其内容
        } else {
            throw new IllegalArgumentException("未能从返回内容中提取有效的 JSON 数组");
        }
        System.out.println(jsonAnswer);

        List<Map<String, String>> parsedList = objectMapper.readValue(jsonAnswer, List.class);
        List<Medication> Medications = new java.util.ArrayList<>();
        System.out.println();
        for (Map<String, String> parsed : parsedList) {
            Medication Medication = new Medication();
            System.out.println(parsed.get("context"));
            Medication.setContext(parsed.get("context"));
            Medication.setTime(LocalTime.parse(parsed.get("time")));
            Medication.setDate(LocalDate.parse(parsed.get("date")));
            Medication.setUserId(userId);
            Medications.add(medicationService.saveMedication(Medication));
        }

        return Medications;
    }
    @DeleteMapping("/user/{userId}")
    public void deleteMedicationsByUserId(@PathVariable Long userId) {
        System.out.println("zz");
        medicationService.deleteByUserId(userId);
    }


    @DeleteMapping("/user/{userId}/{date}")
    public void deleteMedicationsByUserIdAndDate(
            @PathVariable Long userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        medicationService.deleteByUserIdAndDate(userId, date);
    }

    @DeleteMapping("/user/{userId}/{date}/{time}")
    public void deleteMedicationsByUserIdAndDateAndTime(
            @PathVariable Long userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) LocalTime time) {
        medicationService.deleteByUserIdAndDateAndTime(userId, date, time);
    }
}
